<template>
  <div class="login login-container page-container">
    <van-nav-bar title="注册/登录" @click-left="onClickLeft">
      <template slot="left">
        <van-icon name="cross" size="18" @click="$router.back()"/>
      </template>
    </van-nav-bar>

    <!-- Field 是基于 Cell 实现的，可以使用 CellGroup 作为容器来提供外边框。 -->
    <van-cell-group>
      <van-field v-model="user.value" label="文本" placeholder="请输入用户名"/>
    </van-cell-group>
    <!-- <van-icon name="phone-circle-o" /> -->

    <ValidationObserver ref="form">
      <ValidationProvider name="手机号" rules="required|mobile">
        <van-field
          v-model="user.mobile"
          left-icon="phone-circle-o"
          type="tel"
          maxlength="11"
          placeholder="请输入手机号"
        />
      </ValidationProvider>
      <ValidationProvider name="验证码" rules="required|code">
        <van-field v-model="user.code" ref="codeField" placeholder="短信验证码">
          <van-icon slot="left-icon" class-prefix="icon" name="mima"></van-icon>
            <van-button size="small" slot="button"
              :disabled="isSending"
              :type="isSending ? 'default': 'primary'" @click="onSendCode">
              <van-count-down v-if="isSending"  ref="countDown" :time="1000 * 6" format="ss s"></van-count-down>
              <span v-else>发送验证码</span>
            </van-button>
        </van-field>
      </ValidationProvider>
    </ValidationObserver>

    <!-- 登录按钮 -->
    <div class="login-btn-box">
      <van-button color="#6db4fb" type="info" @click="onLogin">登录</van-button>
    </div>
    <!-- /登录按钮 -->
    <van-divider>账号：13911111111 密码：246810</van-divider>
    <van-divider>如果收不到验证码，请使用万能验证码：246810</van-divider>
  </div>
</template>

<script>
import { login, sendSmsCode } from '@/api/user'
import { Toast } from 'vant'
import { validate } from 'vee-validate'

export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        value: '',
        mobile: '13718526927',
        code: '246810'
      },
      isSending: false
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    async onLogin () {
      // 表单验证
      const isValid = await this.$validateForm(this.$refs.form)
      if (!isValid) {
        return
      }

      this.$toast.loading({
        duration: 0, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: '登录中...' // 提示消息
      })

      try {
        const res = await login(this.user)

        // res.data.data => { token: 'xxx', refresh_token: 'xxx' }
        this.$store.commit('setUser', res.data.data)

        this.$store.dispatch('updateProfile')

        // 提示 success 或者 fail 的时候，会先把其它的 toast 先清除
        this.$toast.success('登录成功')

        // 跳转到首页
        const redirect = this.$route.query.redirect || '/'
        this.$router.replace(redirect)
      } catch (err) {
        console.log('登录失败', err)
        this.$toast.fail('登录失败，手机号或验证码错误')
      }
    },

    async onSendCode () {
      const { mobile } = this.user
      // 校验手机号码是否有效
      const validateResult = await validate(mobile, 'required|mobile', {
        name: '手机号码'
      })

      if (!validateResult.valid) {
        this.$toast(validateResult.errors[0])
        return
      }
      // 显示倒计时
      this.isSending = true

      // 让验证码输入框聚焦
      // this.$refs["codeField"].focus()
      // this.$refs.codeField.focus()

      // 开始倒计时
      this.$nextTick(() => {
        this.$refs.countDown.start()
      })

      // 发送短信
      try {
        // await sendSmsCode(mobile)
        console.log(sendSmsCode)
      } catch (err) {
        console.log('发送失败', err)
      }
    },
    onClickLeft () {
      Toast('返回')
    },
    onClickRight () {
      Toast('按钮')
    },
    testClick (e) {
      e.stopPropagation()
    }
  }
}
</script>

<style scoped lang="less">
.login {
  .login-btn-box {
    padding-top: 20px;
    .van-button {
      width: 100%;
    }
  }
}
</style>
